use anyhow::Result;
use napi_derive_ohos::napi;
use sevenz_rust2::{ArchiveEntry, ArchiveReader, Password};
use crate::file_info::FileInfo;

#[napi]
pub struct Decompress {}

#[napi]
impl Decompress {
    #[napi]
    pub async fn read_entries(src_path: String, passwd: String) -> Vec<FileInfo> {
        let mut files = vec![];
        let pwd = Password::from(passwd.as_str());
        if let Ok(mut sz) = ArchiveReader::open(&src_path, pwd.into()) {
            let _ = sz.for_each_entries(|entry: &ArchiveEntry, _| {
                let info = FileInfo::new(entry);
                files.push(info);
                Ok(true)
            });
        }
        files
    }

    #[napi]
    pub async fn decompress_file(src_path: String, dest: String) -> Result<()> {
        sevenz_rust2::decompress_file(src_path, dest)?;
        Ok(())
    }

    #[napi]
    pub async fn decompress_file_with_password(
        src_path: String,
        dest: String,
        passwd: String,
    ) -> Result<()> {
        let pwd = Password::from(passwd.as_str());
        sevenz_rust2::decompress_file_with_password(src_path, dest, pwd)?;
        Ok(())
    }
}
